import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import Button from '@kuiper-components/button';
import Dialog from '@kuiper-components/dialog';

import Icon from '../../components/Icon';
import Empty from '../../components/empty/EmptyData';
import { AVILIABLE_STATUS_MAP } from '../../../common/constants';
import * as formatter from '../../../common/formatter';
import s from './TaskResult.module.css';

const fields = [
	{ label: '监测点', field: 'area' },
	{
		label: '监测类型',
		field: 'networkDisplayName',
	},
	{ label: '监测时间', field: 'endTime', render: formatter.datetime },
	{ label: '响应服务器IP', field: 'ip' },
	{ label: 'HTTP响应长度', field: 'contentLength', render: x => `${x} B` },
	{ label: '响应状态码', field: 'statusCode' },
	{ label: 'DNS解析时间', field: 'dnsTime', render: formatter.millisecond },
	{
		label: '服务器连接耗时',
		field: 'connectTime',
		// eslint-disable-next-line react/display-name
		render: (connectTime, { sslShakeTime }) => {
			return (
				<span>
					{connectTime > 0 ? formatter.millisecond(connectTime) : 0}
					{sslShakeTime > 0
						? `（SSL握手时间：${formatter.millisecond(
								sslShakeTime < 0 ? 0 : sslShakeTime
						  )}）`
						: ''}
				</span>
			);
		},
	},
	{
		label: '服务器响应耗时',
		field: 'respTime',
		render: formatter.millisecond,
	},
	{
		label: '内容下载时间',
		field: 'downloadTime',
		render: formatter.millisecond,
	},
	{ label: '总响应时间', field: 'totalTime', render: formatter.millisecond },
	{ label: '发送包数量', field: 'packetsTransmitted',
		render: packetsTransmitted => packetsTransmitted ? packetsTransmitted + '个' : '- -' },
	{ label: '接受包数量', field: 'packetsReceived',
		render: (packetsReceived, row) => (row?.packetsTransmitted  || packetsReceived) ? packetsReceived + '个' : '- -' },
	{ label: '丢包率', field: 'lossRate', render: (lossRate, row) => (isNaN(lossRate) || !row?.packetsTransmitted) ? '- -' : (lossRate * 100) + '%' },
	{
		label: '监测结果',
		field: 'securityStatus',
		// eslint-disable-next-line react/display-name
		render: securityStatus => (
			<span className={(s.securityStatus, s[securityStatus])}>
				{AVILIABLE_STATUS_MAP[securityStatus]}
			</span>
		),
	},
];

export default function TaskResult({ className, result, text, taskType, type='default', withoutIcon=false }) {
	const [dialogVisible, setDialogVisible] = React.useState(false);
	return (
		<>
			{type === 'default' ? <Button
				link
				className={cn(className, s.taskResult, {[s.cd]: withoutIcon})}
				onClick={!withoutIcon ? () => setDialogVisible(true) : () => {}}
			>
				<span className={cn(s[result.securityStatus])}>
					{text || AVILIABLE_STATUS_MAP[result.securityStatus]}
				</span>
				{!withoutIcon && <Icon
					type="right-circle"
					className={cn(s.icon, s[result.securityStatus])}
				/>}
			</Button> : <Button link primary
				onClick={() => setDialogVisible(true)}>查看详情</Button>}
			<Dialog
				visible={dialogVisible}
				wrapClassName={s.dialog}
				title="监测详情"
				onClose={() => setDialogVisible(false)}
			>
				<div className={s.content}>
					<div className={s.fields}>
						{fields.reduce((arr, { field, label, render }) => {
							let content = result[field];
							if (content || (taskType === 'ping' && ['packetsTransmitted', 'packetsReceived', 'lossRate'].includes(field))) {
								if (render) content = render(content, result);
								arr.push(
									<div key={label || field} className={s.item}>
										<div className={s.label}>{label}：</div>
										<div className={s.info}>{content}</div>
									</div>
								);
							}
							return arr;
						}, [])}
					</div>
					<div className={s.cutLine}></div>
					<div className={s.response}>
						<div className={s.title}>{taskType === 'http' ? 'HTTP/HTTPS ' : 'PING'}快照</div>
						{result.response ? (
							<pre className={s.header}>{result.response}</pre>
						) : result.traffics ? (
							<pre className={s.header}>{result.traffics}</pre>
						) : (
							<Empty className={cn(s.header, s.empty)} />
						)}
					</div>
				</div>
				<div className={s.btnContainer}>
					<Button primary onClick={() => setDialogVisible(false)}>
						关闭
					</Button>
				</div>
			</Dialog>
		</>
	);
}

TaskResult.propTypes = {
	className: PropTypes.string,
	securityStatus: PropTypes.string.isRequired,
	text: PropTypes.string,
	result: PropTypes.shape({
		securityStatus: PropTypes.string.isRequire,
		respTime: PropTypes.number.isRequired,
		response: PropTypes.string,
	}).isRequired,
	taskType: PropTypes.string.isRequired,
};

TaskResult.defaultProps = {
	className: s.taskResult,
	taskType: 'ping',
};
